﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Samples.BcdSampleLib;
using ROOT.WMI;
using System.Diagnostics;
using System.IO;

namespace BCDVHD
{
    class BCDHelper
    {
        public static List<KeyValuePair<string, string>> EnumerateEntries()
        {
            List<KeyValuePair<string, string>> lv = new List<KeyValuePair<string, string>>();
            List<string> guidList = BcdStore_API.GetBootManagerGUIDEntriesDisplayListAsList();
            if (guidList == null)
            {
                throw new Exception("trouble getting guid list");//TODO:make exception
            }


            foreach (string guid in guidList)
            {
                string descrip = BcdStore_API.GetDescriptionForGuid(guid, "");
                if (descrip == null)
                {
                    descrip = guid; // if no description default to showing guid, this is how the actual boot loader does it also
                }
                lv.Add(new KeyValuePair<string, string>(guid, descrip));



            }
            return lv;



        }


        internal static void CreateCopy(string bootguid, string vhd, string description)
        {
            string ex;
            Guid g=BcdStore_API.CloneExistingOSEntry2(bootguid, description, "",  out ex); 
            if (g ==Guid.Empty)
                throw new Exception(ex);
            
            string val = "{" + g.ToString() + "}";
            
            //OK, so make hanselmann's modifications after clone
            string vhdPar = "[" + vhd.Substring(0, 2) + "]" + vhd.Substring(2);
            //BcdObject clone = new BcdObject(BcdStore_API.ImpersonationScope,val, "");
            //clone.SetObjectElement
            string Temp = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), Path.GetTempFileName() + ".bat");
            string var=string.Format("bcdedit /set {0} device vhd={1} {2}", val, vhdPar,Environment.NewLine);
            var += string.Format("bcdedit /set {0} osdevice vhd={1} {2}", val, vhdPar, Environment.NewLine);
            var += string.Format("bcdedit /set {0} detecthal on {1}", val, Environment.NewLine);
            var += "pause";
            File.WriteAllText(Temp, var);
            Process.Start(Temp);
        }
    }
}
